<template>
  <div class="list-wrap-com">
    <div
      class="list-item"
      v-for="(item, index) in list"
      :key="index"
      :class="{ active: item.id === current }"
      @click="changeCurrent(item)"
    >
      <div class="title-wrap">
        <p class="text-over">
          <el-tooltip class="box-item" effect="dark" :content="item.name" placement="top-start">
            <p class="text-over">{{ item.name }}</p>
          </el-tooltip>
        </p>
        （{{ item.records }}/{{ item.restrict }}）
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";

const emit = defineEmits(["change"]);
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  default: {
    type: String,
    default: ""
  }
});

const current = ref(null);
const currentObj = ref(null);

defineExpose({
  currentObj
});

watch(
  () => props.list,
  val => {
    if (val.length > 0) {
      if (props.default) {
        current.value = props.default;
        currentObj.value = props.list.find(item => item.id === props.default);
      } else {
        current.value = props.list[0].id;
        currentObj.value = props.list[0];
      }
    }
  },
  {
    deep: true
  }
);

const changeCurrent = item => {
  if (current.value !== item.id) {
    current.value = item.id;
    currentObj.value = item;
  }
  emit("change", item.id);
};
</script>

<style lang="scss" scoped>
.list-wrap-com {
  .text-over {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  p {
    margin: 0;
    padding: 0;
  }
  .active {
    background-color: #d9e8ff;
    color: #007dff;
  }
  .list-item {
    cursor: pointer;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    font-size: 14px;
    &:not(:last-of-type) {
      margin-bottom: 10px;
    }
    .title-wrap {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
